/*
 * @Author: your name
 * @Date: 2021-11-01 15:58:05
 * @LastEditTime: 2022-01-18 11:30:47
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \star-cat-h5\src\axios\request.js
 */
import axios from 'axios'
import {
    getToken
} from '@/util/auth'
const METHOD = {
    GET: 'get',
    POST: 'post'
}
/**
 * 网络请求
 * @param method 方法
 * @param url 接口地址
 * @param params 参数
 * @returns {Promise<any>}
 */
// 错误和失败信息都在这里进行处理，界面中调用的时候只处理正确数据即可
function request(method, url, params) {
    return new Promise((resolve, reject) => {
        axios({
            method: method,
            url: url,
            params: params,
            data: params,
            headers: {
                token: getToken()
            }
        }).then((res) => {
            if (res.data.code == 1) { // 0 是请求成功
                resolve(res.data.data);
            } else { // 其他情况返回错误信息，根据需要处理
                reject(res.data.msg);
            }
        }).catch((error) => {
            const status =
                (error.response &&
                    error.response.status &&
                    error.response.status) ||
                '';
            const data = (error.response && error.response.data) || {};
            if (data.msg) {
                reject(data.msg)
            }
            if (
                error.code == 'ECONNABORTED' &&
                error.msg.indexOf('timeout') != -1
            ) {
                reject('请求超时~~')
            }
            if (status === 401) {
                reject('登录过期,请重新登录')
            }
            if (status === 404) {
                reject('接口404报错')
            }
            if (status === 500) {
                reject('服务器错误')
            }
            reject(error)
        });
    });
}


export function get(url, params, showError) {
    return request(METHOD.GET, url, params, showError);
}

export function post(url, params, showError) {
    return request(METHOD.POST, url, params, showError);
}